<?php

namespace App\Console\Commands\Activity;

use App\Library\FeiShu\SendFs;
use App\Models\Activity\ActivityFeedbackNoticeLogModel;
use App\Models\Activity\ActivityModel;
use App\Models\Activity\ActivityShopJoinModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\System\SystemNotifyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;

class ActivityEndRemindFeedback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'activity:activityEndRemindFeedback {activityId?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '活动结束后提醒门店上传反馈通知';// 每10分钟查询一次

    public function handle()
    {
        $activityId = (int)$this->argument('activityId');
        $username   = '系统';

        $time = strtotime(date('Y-m-d H:i'));
        $nowWeek = date('w');        // 今天是周几

        ActivityModel::query()
            ->when(
                $activityId, function ($query) use ($activityId) {
                $query->where('id', $activityId);// 活动id
            }
            )
            ->where('remindSwitch', 1)// 提醒开关 [ 1:开启
            ->where('remindStartTime', '<=', $time)// 提醒开始时间
            ->where('remindEndTime', '>', $time)  // 提醒结束时间
            ->where('remindDailyTime', '<=', date('H:i:00'))  // 提醒结束时间
            ->chunkById(
                10, function ($item) use ($username, $time, $nowWeek) {

                foreach ($item as $v) {
                    if (!$v->systemNotifyCenterId) {// 没有消息id
                        continue;
                    }

                    $systemNotifyCenterModel = SystemNotifyCenterModel::query()->where("id", $v->systemNotifyCenterId)->first();
                    // 消息被删除 ｜｜ 消息被禁用  不发送消息
                    if(!$systemNotifyCenterModel || $systemNotifyCenterModel->status == SystemNotifyCenterModel::NOTIFY_STATUS_4){
                        continue;
                    }

                    $remindCycle = json_decode($v['remindCycle'] ?? '', true) ?? [];
                    if (!$remindCycle || !in_array($nowWeek, $remindCycle)) {// 不在通知周期
                        continue;
                    }

                    $diffDaily = $time - strtotime(date('Y-m-d ' . $v['remindDailyTime']));

                    if ($diffDaily < 0 || $diffDaily > 3600) {// 每日通知时间-当前时间
                        continue;
                    }

                    $noticeLog = ActivityFeedbackNoticeLogModel::query()
                        ->where('activityId', $v->id)
                        ->whereBetween('createdAt', [strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))])
                        ->count();

                    $this->info("activityId:{$v->id} log:". $noticeLog);

                    if ($noticeLog) {// 查询今天有没有当前活动回传提醒记录
                        continue;
                    }

                    // 未报名的活动人员
                    $data = self::getNoticeShopIds($v->id);
                    if (!$data['allUserList']) {
                        continue;
                    }

                    $model                       = new ActivityFeedbackNoticeLogModel();
                    $model->activityId           = $v->id;                                                      // activity.id
                    $model->systemNotifyCenterId = $v->systemNotifyCenterId;                                    // 消息id system_notify_center.id
                    $model->remindDailyTime      = $v->remindDailyTime;                                         // 每日通知时间
                    $model->noticeTime           = $time;                                                       // 实际通知时间
                    $model->shopIdList           = json_encode($data['allShopList'], JSON_UNESCAPED_UNICODE);   // 通知门店ids
                    $model->userIdList           = json_encode($data['allUserList'], JSON_UNESCAPED_UNICODE);   // 通知用户ids
                    $model->save();

                    Log::info(
                        'debug_SystemNotify', [
                            'activityId'           => $v->id,
                            'name'                 => $v->name,
                            'systemNotifyCenterId' => $v->systemNotifyCenterId,
                            'userIdList'           => $data['allUserList'],
                        ]
                    );

                    // 发消息通知
                    SystemNotifyService::preSend($v->systemNotifyCenterId, $data['allUserList']);

                    // 推送品牌活动消息
                    self::sendFs($v->id, $v->name, $v->systemNotifyCenterId, $username);

                    dump("活动ID: {$v->id} 消息ID: {$v->systemNotifyCenterId} ");
                }
            }
            );


    }

    /**
     * 获取未回传的门店id-未报名的活动人员
     * @param int $activityId
     * @return array
     */
    public static function getNoticeShopIds(int $activityId): array
    {
        $allUserList = $allShopList = [];
        ActivityShopJoinModel::query()
            ->where('activityId', $activityId)
            ->where('status', ActivityShopJoinModel::STATUS_3)// 已完成
            ->where('feedbackStatus', ActivityShopJoinModel::FEEDBACK_STATUS_0)// 待回传
            ->select(['id', 'shopId'])
            ->chunkById(
                500, function ($item) use ($activityId, &$allUserList, &$allShopList) {

                $notFeedbackShopIds = array_column($item->toArray(), 'shopId');
                if ($notFeedbackShopIds) {
                    $allShopList = array_merge($allShopList, $notFeedbackShopIds);
                    $userList    = RmsUserRemote::getShopManagerUserByShopId($notFeedbackShopIds)['lists'] ?? [];
                    if ($userList) {
                        $allUserList = array_merge($allUserList, array_column($userList, 'userId'));
                    }
                }
            }
            );

        // 未报名的活动人员
        $allUserList = array_values(array_unique($allUserList));
        $allShopList = array_values(array_unique($allShopList));
        return [
            'allShopList' => $allShopList,
            'allUserList' => $allUserList,
        ];
    }

    /**
     * 推送品牌活动消息
     * @param int $activityId
     * @param string $activityName
     * @param int $messageId
     * @param string $username
     * @throws \Exception
     */
    public function sendFs(int $activityId, string $activityName, int $messageId, string $username)
    {
        $title = "推送{$activityName}回传通知消息";
        BuildFs::newRobot(SendFs::ROBOT_WARNING)
            ->setTitleContent(
                $title,
                "推送人:{$username}" . PHP_EOL . '活动ID:' . $activityId . PHP_EOL . '消息ID:' . $messageId . PHP_EOL
            )
            ->setAtUid('2c54915f') //胡迪
            ->send();
    }
}
